package cn.qyd.concurrentcollection;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author 邱运铎
 * @date 2024-03-22 22:36
 */
public class DelayQueueDemo {
    static class DelayElement implements Delayed {
        private long delay;
        private String name;

        public DelayElement(String name, long delay) {
            this.name = name;
            this.delay = System.currentTimeMillis() + delay;
        }

        public String getName() {
            return name;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(delay - System.currentTimeMillis(),TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return Long.compare(this.delay, ((DelayElement)o).delay);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayElement> queue = new DelayQueue<>();

        queue.put(new DelayElement("这是一个延迟五秒的任务",5000));

        System.out.println("取一个元素");
        DelayElement element = queue.take();
        System.out.println(element.getName());
    }
}
